//
//  BHStadiumDetailViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/7/1.
//

import UIKit

class BHStadiumDetailViewController: BHBaseViewController {

    lazy var navigationBar: BHCompetitionDetailNavBar = { [unowned self] in
        let view = BHCompetitionDetailNavBar.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.begainY)
        view.backgroundColor = UIColor.color_34CE98.withAlphaComponent(0.0)
        view.title_label.text = "场馆详情"
        view.shareBtn.isHidden = true
        view.delegate = self
        return view
    }()
    
    lazy var headerView: BHStadiumDetailHeaderView = {
        let view = BHStadiumDetailHeaderView.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: BHStadiumDetailHeaderView.headerHeight)
        return view
    }()
    
    lazy var tableView: UITableView = { [unowned self] in
        let view = UITableView.buildTableView(style: .grouped)
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height)
        view.delegate = self
        view.dataSource = self
        return view
    }()
    
    lazy var serviceManager: BHStadiumServiceManager = {
        let manager = BHStadiumServiceManager.init()
        return manager
    }()
    
    lazy var introduceCell: BHHtmlContentWebCell = { [weak self] in
        let cell = self?.tableView.dequeueReusableCell(withIdentifier: "BHHtmlContentWebCell", for: IndexPath.init(row: 0, section: 0)) as! BHHtmlContentWebCell
        cell.clipsToBounds = true
        return cell
    }()
    
    var stadiumId: String = ""
    fileprivate var introduceHeight: CGFloat = 0
    fileprivate var introduceFlag: Bool = false
    fileprivate var detailModel: BHStadiumDetailModel = BHStadiumDetailModel.init()
    fileprivate var coachArray: [BHCoacheModel] = []
    fileprivate var gameArray: [BHStadiumDetailGameModel] = []
    fileprivate var playArray: [BHStadiumDetailPlayModel] = []
    fileprivate var productArray: [BHStadiumDetailGoodModel] = []
    fileprivate var productType: Int = 0 // 选择的商品类型
    fileprivate var productFlag: Bool = false
    fileprivate var remarkScrollView: UIScrollView?
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.bh_navigationBar.removeFromSuperview()
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.navigationBar)
        self.regisetCell()
        self.tableView.tableHeaderView = self.headerView
        
        self.serviceManager.stadiumId = self.stadiumId
        self.oberserNetResponse()
        self.serviceManager.refreshStadiumService()

        self.tableView.addRefresh { [weak self] in
            self?.productType = 0
            self?.serviceManager.refreshStadiumService()
        }
        
        self.introduceCell.webCellCallRealHeightBlock = { [weak self] height in
            self?.introduceHeight = height
            self?.tableView.reloadData()
        }
        
        self.headerView.phoneBtn.addBtnAction(action: {[weak self] (_) in
            if self?.detailModel.contactNumber.isEmpty == true {
                return
            }
            
            self?.begainTel()
            
        }, for: .touchUpInside)
    }
    
    private func regisetCell()  {
        self.tableView.register(BHStadiumSuitTypeCell.self, forCellReuseIdentifier: "BHStadiumSuitTypeCell")
        self.tableView.regiseterNib(nibName: "BHStadiumSuitInfoCell")
        self.tableView.regiseterNib(nibName: "BHStadiumCoachCell")
        self.tableView.regiseterNib(nibName: "BHStadiumCompetitionInfoCell")
        self.tableView.regiseterNib(nibName: "BHStadiumFunInfoCell")
        self.tableView.register(BHHtmlContentWebCell.self, forCellReuseIdentifier: "BHHtmlContentWebCell")
    }

    
    private func begainTel() {
        BHCommonTool.telAct(self.detailModel.contactNumber) { (open) in
            if open == false {
                BHToast.toast(text: "当前设备暂不支持拨打电话")
            }
        }
    }
}
extension BHStadiumDetailViewController: BHCompetitionDetailNavBarDelegate {
    func navigationBarDidBackAction() {
        self.navigationController?.popViewController(animated: true)
    }
    // 0 是分享 1是收藏
    func navigationBarDidShareOrCollectAction(type: Int, collectOrNot: Bool) {
        if type == 1 {
            self.collectOrNotService()
        }
    }
}

extension BHStadiumDetailViewController: UITableViewDataSource {
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.remarkScrollView = scrollView
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if self.remarkScrollView != nil {
            if  scrollView != self.remarkScrollView! {
                return
            }
        }
        
        if scrollView == self.tableView {
            if scrollView.contentOffset.y <= 0 {
                self.navigationBar.backgroundColor = UIColor.color_34CE98.withAlphaComponent(0.0)
            }else {
                var alpha = scrollView.contentOffset.y/UIScreen.begainY
                if alpha > 1 {
                    alpha = 1
                }
                self.navigationBar.backgroundColor = UIColor.color_34CE98.withAlphaComponent(alpha)
            }
            
        }
    }
   
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        self.remarkScrollView = nil
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 5
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1 { // 产品
            if self.productArray.count == 0 {
                return 0
            }else {
                let allModel = self.productArray[0]
                if allModel.goods.count == 0 {
                    return 0
                }else {
                    let model = self.productArray[self.productType]
                    if self.productFlag == false && model.goods.count > 2 {
                        return 3
                    }
                    return model.goods.count+1
                }
            }
        }
        if section == 2 { // 教练
            if self.coachArray.count == 0 {
                return 0
            }
            return 1
        }
        
        if section == 3 { // 赛事
            return self.gameArray.count
        }
        if section == 4 { // 赛事
            return self.playArray.count
        }
        return 1
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if self.introduceFlag == false {
                if self.introduceHeight > 150 {
                    return 150
                }
            }
            return self.introduceHeight
        }else if (indexPath.section == 1) {
            if indexPath.row == 0 {
                return BHStadiumSuitTypeCell.height
            }else {
                return BHStadiumSuitInfoCell.cellHeight
            }
        }else if indexPath.section == 2 { // 教练
            return 160
        }else if indexPath.section == 3 { // 赛事
            return 70
        }else if indexPath.section == 4 { // 活动
            return 75
        }
       return 0
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            if self.productArray.count == 0 {
                return CGFloat.leastNormalMagnitude
            }
            let allModel = self.productArray[0]
            if allModel.goods.count == 0 {
                return CGFloat.leastNormalMagnitude
            }
        }
        if section == 2 {
            if self.coachArray.count == 0 {
                return CGFloat.leastNormalMagnitude
            }
        }
        if section == 3 {
            if self.gameArray.count == 0 {
                return CGFloat.leastNormalMagnitude
            }
        }
        if section == 3 {
            if self.playArray.count == 0 {
                return CGFloat.leastNormalMagnitude
            }
        }
        return 55
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 0 { // 介绍
            if self.introduceHeight > 150 {
                return BHStadiumShowMoreFooter.moreHeight
            }
        }
        if section == 1 { // 商品
            if self.productArray.count != 0 {
                let model = self.productArray[self.productType]
                let array = model.goods
                if array.count > 2 {
                    return BHStadiumShowMoreFooter.moreHeight
                }
            }
        }
        return CGFloat.leastNormalMagnitude
    }
    
}

extension BHStadiumDetailViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view  = BHStadiumSecHeaderView.loadFromXib()
        view.moreBtn.isHidden = true
        if section == 0 {
            view.name_label.text = "商家介绍"
        }else if (section == 1) {
            if self.productArray.count == 0 {
                return nil
            }
            let allModel = self.productArray[0]
            if allModel.goods.count == 0 {
                return nil
            }
            view.name_label.text = "购买"
        }else if section == 2 { // 教练
            if self.coachArray.count == 0 {
                return nil
            }
            view.name_label.text = "教练"
        }else if section == 3 { // 赛事
            if self.gameArray.count == 0 {
                return nil
            }
            view.name_label.text = "赛事"
        }else if section == 4 { // 活动
            if self.playArray.count == 0 {
                return nil
            }
            view.name_label.text = "活动"
        }
        view.clipsToBounds = true
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 0 {
            if self.introduceHeight > 150 {
                let view = BHStadiumShowMoreFooter.loadFromXib()
                view.showMoreBtn.isSelected = self.introduceFlag
                view.showMoreBtn.addBtnAction(action: {[weak self] (_) in
                    self?.introduceFlag = !(self?.introduceFlag ?? false)
                    
                    tableView.reloadData()
                }, for: .touchUpInside)
                return view
            }
        }
        if section == 1 {
            if self.productArray.count != 0 {
                let model = self.productArray[self.productType]
                let array = model.goods
                if array.count > 2 {
                    let view = BHStadiumShowMoreFooter.loadFromXib()
                    view.showMoreBtn.isSelected = self.productFlag
                    view.showMoreBtn.addBtnAction(action: {[weak self] (_) in
                        self?.productFlag = !(self?.productFlag ?? false)
                        tableView.reloadData()
                    }, for: .touchUpInside)
                    return view
                }
            }
        }
        return nil
    }
 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            return self.introduceCell
        }else if (indexPath.section == 1) {
            if indexPath.row == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "BHStadiumSuitTypeCell", for: indexPath) as! BHStadiumSuitTypeCell
                cell.choseIndex = self.productType
                cell.stadiumProArray = self.productArray
                cell.didChoseSuitBlock = { [weak self] index in
                    self?.productType = index
                    tableView.reloadData()
                }
                return cell
            }else {
                let cell = tableView.dequeueReusableCell(withIdentifier: "BHStadiumSuitInfoCell", for: indexPath) as! BHStadiumSuitInfoCell
                let model = self.productArray[self.productType]
                let infoModel = model.goods[indexPath.row-1]
                cell.model = infoModel
                cell.buyBtn.addBtnAction(action: { (_) in
                    BHRouter.shared.bh_goProductDetail(productId: infoModel.goodId)
                }, for: .touchUpInside)
                return cell
            }
        }else if indexPath.section == 2 { // 教练
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHStadiumCoachCell", for: indexPath) as! BHStadiumCoachCell
            cell.coachArray = self.coachArray
            cell.coachDidSelectEntryDetailBlock = { (_, coachId) in
                BHRouter.shared.bh_goCoachDetail(coachId: coachId)
            }
            return cell
        }else if indexPath.section == 3 { // 赛事
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHStadiumCompetitionInfoCell", for: indexPath) as! BHStadiumCompetitionInfoCell
            let model = self.gameArray[indexPath.row]
            cell.model = model
            return cell
        }else if indexPath.section == 4 { // 活动
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHStadiumFunInfoCell", for: indexPath) as! BHStadiumFunInfoCell
            let model = self.playArray[indexPath.row]
            cell.model = model
            return cell
        }
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 1 {
            if indexPath.row != 0 {
                let model = self.productArray[self.productType]
                let infoModel = model.goods[indexPath.row-1]
                BHRouter.shared.bh_goProductDetail(productId: infoModel.goodId)
            }
        }
        if indexPath.section == 3 { // 赛事
            let model = self.gameArray[indexPath.row]
            BHRouter.shared.bh_goGameDetail(gameId: model.gameId)
        }
        
        if indexPath.section == 4 { // 活动
            let model = self.playArray[indexPath.row]
            BHRouter.shared.bh_goFunDetail(funId: model.playId)
        }
    }
}



extension BHStadiumDetailViewController {
  
    func oberserNetResponse()  {
        // 主详情回调
        self.serviceManager.stadiumDetailMainResponseBlock = { [weak self] model in
            self?.detailModel = model
            self?.navigationBar.collected = model.ifAttention == 1
            self?.headerView.model = model
            self?.introduceCell.htmlText = model.introduce
        }
        // 教练列表
        self.serviceManager.stadiumDetailCoachResponseBlock = { [weak self] coachArray in
            self?.coachArray = coachArray
        }
        // 赛事
        self.serviceManager.stadiumDetailGameResponseBlock = { [weak self] gameArray in
            self?.gameArray = gameArray
        }
        // 商品
        self.serviceManager.stadiumDetailProductResponseBlock = { [weak self] productArray in
            self?.productArray = productArray
        }
        // 活动
        self.serviceManager.stadiumDetailPlayResponseBlock = { [weak self] playArray in
            self?.playArray = playArray
        }
        
        // 所有接口都走了
        self.serviceManager.stadiumResponseCompleteHandler = { [weak self] in
            self?.tableView.endRefresh()
            self?.tableView.reloadData()
        }
    }
    
    func collectOrNotService()  {
        SVProgressHUD.show()
        BHCommonService.collectOrNotService(type: 2, businessId: self.stadiumId) {[unowned self] (success, errorMsg) in
            SVProgressHUD.dismiss()
            if success == true {
                if self.detailModel.ifAttention == 1 {
                    self.detailModel.ifAttention = 0
                    BHToast.toast(text: "收藏已取消")
                }else {
                    self.detailModel.ifAttention = 1
                    BHToast.toast(text: "已收藏")
                }
                self.navigationBar.collected = self.detailModel.ifAttention == 1
            }
        }
    }
    
   
}
